package com.iwhalecloud.bss.kite.cucc.web.controller.shoppingcart;

import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.kite.cart.client.api.cart.operate.IOperateKiteShoppingCartService;
import com.iwhalecloud.bss.kite.cart.client.api.cart.query.IQueryKiteCartService;
import com.iwhalecloud.bss.kite.cart.client.api.cart.query.IQueryKiteShoppingCartService;
import com.iwhalecloud.bss.kite.cart.client.dto.cart.KiteCartGroupInstDTO;
import com.iwhalecloud.bss.kite.cart.client.dto.req.DraftKiteCartReqDTO;
import com.iwhalecloud.bss.kite.cart.client.dto.req.KiteCartAddRequestDTO;
import com.iwhalecloud.bss.kite.cart.client.dto.req.KiteCartCommitRequestDTO;
import com.iwhalecloud.bss.kite.cart.client.dto.req.KiteCartDeleteRequestDTO;
import com.iwhalecloud.bss.kite.cart.client.dto.req.KiteCartGetRequestDTO;
import com.iwhalecloud.bss.kite.cart.client.dto.req.KiteCartModifyRequestDTO;
import com.iwhalecloud.bss.kite.cart.client.dto.req.KiteCartQueryRequestDTO;
import com.iwhalecloud.bss.kite.client.api.scene.query.IQuerySceneService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.dto.rule.common.DataRuleResult;
import com.iwhalecloud.bss.kite.client.dto.shoppingcart.ShoppingCartGroupInstDTO;
import com.iwhalecloud.bss.kite.common.callclient.service.rule.IRuleTriggerService;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.common.util.RuleResponseUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.shoppingcart.operate.ICuccOperateShoppingCartService;
import com.iwhalecloud.bss.kite.cucc.client.api.shoppingcart.query.ICuccQueryShoppingCartService;
import com.iwhalecloud.bss.kite.cucc.client.dto.cart.CuccKiteCartDeleteRequestDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.cart.KiteCartAcceptReqDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.cart.KiteCartAcceptRspDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.cart.KiteCartRequestDTO;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.util.RuleParamUtils;
import com.ztesoft.bss.base.entity.AttrValue;
import com.ztesoft.bss.common.bo.LoginInfo;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.bss.rul.core.client.dto.common.RuleCommonParam;
import com.ztesoft.bss.rul.core.client.dto.kite.KiteRuleResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Api(tags = {"/kiteCart - 极简购物车"})
@RestController("kiteCart")
@RequestMapping("/kiteCart")
public class KiteCartController {
    @Autowired
    private IOperateKiteShoppingCartService operateShoppingCartService;

    @Autowired
    private ICuccQueryShoppingCartService queryShoppingCartService;

    @Autowired
    private IRuleTriggerService ruleTriggerService;

    @Autowired
    private IQuerySceneService querySceneService;


    @Autowired
    private ICuccOperateShoppingCartService cuccOperateShoppingCartService;




    @ApiOperation(value = "新增购物车")
    @PostMapping("/saveKiteCart")
    public DataResult<String> saveKiteCart(@RequestBody KiteCartAddRequestDTO request) {
        return operateShoppingCartService.saveKiteCart(request);
    }

    @ApiOperation(value = "删除购物车")
    @DeleteMapping("/deleteKiteCart")
    public DataResult<String> deleteKiteCart(@RequestBody KiteCartDeleteRequestDTO request) {
        return operateShoppingCartService.deleteKiteCart(request);
    }

    @ApiOperation(value = "删除购物车分组", notes = "删除购物车分组")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "custId", value = "客户标识", required = true),
        @ApiImplicitParam(name = "groupIds", value = "购物车分组标识", required = true)
    })
    @DeleteMapping("/deleteKiteCartBak")
    public DataResult<Boolean> deleteShoppingCartGroups(@RequestBody CuccKiteCartDeleteRequestDTO request) {

//        DataRuleResult ruleResult = beforeOrderCancelRule(request.getGroupIds());
//        if (ruleResult != null && (RuleConsts.RULE_RESPONSE_FAILURE.equals(ruleResult.getResultCode()) || !ruleResult.getResultObject()
//            .getCheckFlag())) {
//            return ErrorConsts.SUCCESS.getResult(null, ruleResult);
//        }

        return cuccOperateShoppingCartService.deleteShoppingCartGroups(request);

    }
    /**
     * 订单取消前规则
     * @param groupIds
     * @return
     */
    private DataRuleResult beforeOrderCancelRule(List<String> groupIds) {
        List<String> validGroupIds = new ArrayList<>();
        List<String> serviceOfferIds = new ArrayList<>();
        for (String sceneInstId : groupIds) {
            try {
                KiteSceneInst curSceneInst = querySceneService.getSceneInst(sceneInstId);
                if (curSceneInst != null) {
                    validGroupIds.add(curSceneInst.getSceneInstId());
                    serviceOfferIds.add(curSceneInst.getServiceOfferId());
                }
            }
            catch (Exception ex) {
              //  logger.error(ErrorConsts.SYSTEM_ERROR.getErrorCode(), ex, null);
            }
        }
        if (KiteListUtils.isNotEmpty(validGroupIds)) {
            // 订单取消前规则
            RuleCommonParam ruleParam = RuleParamUtils.getRuleParam();
            KiteRuleResponse ruleResponse = ruleTriggerService
                .onBfCancelOrderRule(validGroupIds, serviceOfferIds, ruleParam);
            return RuleResponseUtils.transRuleResponse2RuleResult(ruleResponse);
        }
        return null;
    }
    @ApiOperation(value = "修改购物车")
    @PutMapping("/modifyKiteCart")
    public DataResult<String> modifyKiteCart(@RequestBody KiteCartModifyRequestDTO request) {
        return operateShoppingCartService.modifyKiteCart(request);
    }

    @ApiOperation(value = "提交购物车")
    @PostMapping("/commitKiteCart")
    public DataResult<Boolean> commitKiteCart(@RequestBody KiteCartCommitRequestDTO request) {
         operateShoppingCartService.commitKiteCart(request);
         return ErrorConsts.SUCCESS.getResult(true);
    }

    @ApiOperation(value = "查询购物车列表")
    @GetMapping("/shoppingCartGroups")
    public DataResult<PageInfo<ShoppingCartGroupInstDTO>> queryKiteCarts(KiteCartQueryRequestDTO request) {
        String staffId = request.getStaffId();
        if (KiteStringUtils.isEmpty(staffId)) {
            staffId = ContextUtil.getSimpleLoginInfo().getUserId().toString();
            request.setStaffId(staffId);

        }

        return ErrorConsts.SUCCESS.getResult(queryShoppingCartService.listGroupInstsPage(request));
    }

    @ApiOperation(value = "根据购物车数据初始化场景实例")
    @PostMapping("/createShoppingCartGroups")
    public DataResult<ShoppingCartGroupInstDTO> createShoppingCartGroupInstInfo(KiteCartRequestDTO request) {
        String staffId = request.getStaffId();
        if (KiteStringUtils.isEmpty(staffId)) {
            staffId = ContextUtil.getSimpleLoginInfo().getUserId().toString();
            request.setStaffId(staffId);

        }
        return cuccOperateShoppingCartService.createShoppingCartGroupInstInfo(request);
    }


    @SuppressWarnings("unchecked")
    @ApiOperation(value = "购物车分组列表", notes = "购物车分组列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "custId", value = "客户标识", required = true),
        @ApiImplicitParam(name = "flagCustReception", value = "客户接待页面标识", required = true)
    })
    @GetMapping("/queryKiteCarts")
    public DataResult<List<ShoppingCartGroupInstDTO>> listShoppingCartGroups(KiteCartQueryRequestDTO request) {
        String staffId = request.getStaffId();
        if (KiteStringUtils.isEmpty(staffId)) {
            staffId = ContextUtil.getSimpleLoginInfo().getUserId().toString();
            request.setStaffId(staffId);

        }
        return ErrorConsts.SUCCESS.getResult(queryShoppingCartService.listShoppingCartGroupInsts(request));
    }

    @ApiOperation(value = "购物车详情")
    @GetMapping("/getKiteCartDetail")
    public DataResult<KiteCartGroupInstDTO> getKiteCartDetail(@RequestBody KiteCartGetRequestDTO request) {
        return SpringUtil.getBean(IQueryKiteCartService.class).getKiteCartDetail(request);
    }

    @ApiOperation(value = "通过es查询购物车")
    @GetMapping("/getShoppingCartByEs")
    public DataResult<Long> getShoppingCartByEs(String staffId) {
        return SpringUtil.getBean(IQueryKiteShoppingCartService.class).getShoppingCartIdByEs(staffId);
    }
    @ApiOperation(value = "购物车分组统计", notes = "购物车分组统计")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "custId", value = "客户标识"),
        @ApiImplicitParam(name = "staffId", value = "登录工号标识")

    })
    @GetMapping("/shoppingCartGroupCount")
    public DataResult<Integer> getShoppingCartGroupCount(KiteCartQueryRequestDTO request) {
        if(KiteStringUtils.isEmpty(request.getStaffId())){
            request.setStaffId(ContextUtil.getSimpleLoginInfo().getUserId().toString());
        }

        return ErrorConsts.SUCCESS.getResult(queryShoppingCartService.getShoppingCartGroupCount(request));
    }

    @ApiOperation(value = "根据基础数据初始化购物车数据")
    @PostMapping("/initCartGroupInstInfo")
    public DataResult<KiteCartAcceptRspDTO> initCartGroupInstInfo(@RequestBody KiteCartAcceptReqDTO kiteCartAcceptReqDTO) {
        String staffId = kiteCartAcceptReqDTO.getStaffId();
        if (KiteStringUtils.isEmpty(staffId)) {
            staffId = ContextUtil.getSimpleLoginInfo().getUserId().toString();
            kiteCartAcceptReqDTO.setStaffId(staffId);
        }
        if (KiteStringUtils.isEmpty(kiteCartAcceptReqDTO.getCustId())) {
            String custId = KiteWebContext.getContext().getCustId();
            kiteCartAcceptReqDTO.setCustId(custId);
        }

        kiteCartAcceptReqDTO.setProvinceCode(ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
        kiteCartAcceptReqDTO.setEparchyCode(ContextUtil.getLoginInfo().getUserInfo().getPostLanId());

        return cuccOperateShoppingCartService.initCartGroupInstInfo(kiteCartAcceptReqDTO);
    }

    @ApiOperation(value = "查询购物车融合商品明细")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "sceneInstId", value = "场景id", required = true),
        @ApiImplicitParam(name = "offerId", value = "融合商品id", required = true),
        @ApiImplicitParam(name = "custId", value = "客户id", required = true),
        @ApiImplicitParam(name = "statusCd", value = "状态", required = true),
        @ApiImplicitParam(name = "serviceOfferId", value = "服务工作id", required = true)
    })
    @GetMapping("/queryKiteCartDetails")
    public DataResult<List<ShoppingCartGroupInstDTO>> queryKiteCartDetails(@RequestParam String sceneInstId,@RequestParam String cartId, @RequestParam String offerId, @RequestParam String custId,
                                                                           @RequestParam String statusCd, @RequestParam String serviceOfferId) {
        LoginInfo loginInfo = ContextUtil.getLoginInfo();
        loginInfo.getUserInfo().getExtParams().put("KITE_SCENEINST_CARTID", cartId);
        ContextUtil.setLoginInfo(loginInfo);

        return ErrorConsts.SUCCESS.getResult(queryShoppingCartService.queryKiteCartDetails(sceneInstId,cartId,offerId,custId,statusCd,serviceOfferId));
    }

    @ApiOperation(value = "购物车列表获取客户名称下拉框")
    @GetMapping("/queryShoppingCartCustName")
    public DataResult<List<AttrValue>> queryShoppingCartCustName(String staffId) {
        if (KiteStringUtils.isEmpty(staffId)) {
            staffId = ContextUtil.getSimpleLoginInfo().getUserId().toString();
        }
        return SpringUtil.getBean(IQueryKiteCartService.class).queryShoppingCartCustName(staffId);
    }

    @ApiOperation(value = "购物车实例保存为草稿")
    @PostMapping("/draftKiteCart")
    public DataResult<String> draftKiteCart(@RequestBody DraftKiteCartReqDTO request) {
        return cuccOperateShoppingCartService.draftKiteCart(request);

    }

}
